﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Cat.Helper
{
    class File_helper
    {
        /// <summary>
        ///  文件创建 需要文件路径，尽量是完整的，如果不是完整的则会在当前项目创建
        /// </summary>
        /// <param name="file_path">文件路径</param>
        public void File_existence(String file_path)
        {

            String result = Path.GetExtension(file_path);
        //    Console.WriteLine("获取到文件名('{0}') 扩展名： '{1}'",  file_path, result);
            if (result == "" && (!System.IO.Directory.Exists(file_path)))
            {
                try
                {
                    Directory.CreateDirectory(file_path);
                    Console.WriteLine("文件目录不存在，已创建");

                }
                catch (Exception e)
                {
                    Console.WriteLine("创建文件目录异常：" + e);
                }
            }
            else if (result != "" && !System.IO.File.Exists(file_path))
            {
                try
                {
                    System.IO.File.WriteAllText(file_path, string.Empty, Encoding.UTF8);//记得要销毁占用
                    Console.WriteLine("普通文件不存在，已创建");
                }
                catch (Exception e)
                {
                    Console.WriteLine("创建普通文件异常：" + e);
                }

            }
            else
            {
              //  Console.WriteLine("文件存在，无需创建");
            }
        }
        /// <summary>
        /// 更新日志
        /// </summary>
        /// <param name="path"></param>
        /// <param name="log"></param>
        public void Log_Update(String path, String log) {

            if(log!="")
            System.IO.File.AppendAllText(path, "\r\n" + log);
      //      Static_value.old_url.Add(log);

        }


        public void Open_dictionary(string path) {
            File_existence(path);

            System.Diagnostics.Process.Start("explorer.exe", path);
        }

        /// <summary>
        /// 替换文件名字中的非法字符！
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string ReplaceBadChar(string str)
        {
            if (string.IsNullOrEmpty(str))
                return "";

            StringBuilder rBuilder = new StringBuilder(str);

            foreach (char rInvalidChar in Path.GetInvalidFileNameChars())
                rBuilder.Replace(rInvalidChar.ToString(), string.Empty);

            str = rBuilder.ToString();
            return str;
        }
    }
}
